﻿using System;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;
using Components.Data;

namespace Components.Runtime
{
  public class PageHandler : IHttpHandler
  {
    public bool IsReusable
    {
      get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
      CreatePageInstance(Context.Element.Presentation.PageBinding);

      PageInstance.PreInit += new EventHandler(PageInstance_PreInit);
      PageInstance.Init += new EventHandler(PageInstance_Init);

      ((IHttpHandler)PageInstance).ProcessRequest(context);
    }
    public Page PageInstance { get; private set; }

    private void PageInstance_PreInit(object sender, EventArgs e)
    {
      if (Context.Element != null && Context.Element.Presentation != null)
      {
        Context.Element.Presentation.BindMasterPages(PageInstance);
        Context.Element.Presentation.BindTheme(PageInstance);
      }
    }

    private void PageInstance_Init(object sender, EventArgs e)
    {
      if (Context.Element != null && Context.Element.Presentation != null)
      {
        Context.Element.Presentation.BindControls(PageInstance);
      }
    }

    protected void CreatePageInstance(String physicalPath)
    {
      PageInstance = BuildManager.CreateInstanceFromVirtualPath(physicalPath, typeof(Page)) as Page;
    }
  }
}